const closeAll = function (arr) {
  arr.forEach((item) => {
    item.closed = true
  })
}
const state = {
  appsArray: []
}

const mutations = {
  addAppsArray(state, playload) { // playload 是app
    if (!state.appsArray.length) { // Apps 数组为空
      playload.closed = false // 默认窗口打开
      state.appsArray.push(playload) // 直接插入Apps数组
    } else {
      let target = state.appsArray.find((item) => {
        return item.name === playload.name
      })
      if (target) {
        if (target.url !== playload.url) {
          target.url = playload.url
        }
        target.closed = false
        // this.$nextTick(() => { target.closed = false })
      } else {
        playload.closed = false
        state.appsArray.push(playload)
        // this.$nextTick(() => { this.appsArray[this.appsArray.length - 1].closed = false })
      }
    }
  },
  closeAllApps(state) {
    closeAll(state.appsArray)
  },
  toggleApp(state, playload) { // playload 是app.name
    if (!state.appsArray.length) return
    let target = state.appsArray.find((item) => { return item.name === playload })
    if (!target) return
    if (target.closed) {
      closeAll(state.appsArray) // 关闭其他app
      target.closed = false // 打开
    } else {
      target.closed = true // 关闭
    }
  },
  closeApp(state, playload) { // playload 是app.name
    if (!state.appsArray.length) return
    let target = state.appsArray.find((item) => { return item.name === playload })
    if (!target) return
    target.closed = true
  },
  removeApp(state, playload) {
    let targetIndex = state.appsArray.findIndex((item) => { return item.name === playload })
    state.appsArray[targetIndex].closed = true
    state.appsArray.splice(targetIndex, 1) 
  }
}
const apps = {
  namespaced: true,
  state: state,
  mutations: mutations
  // getters: getters
}
export default apps